package cn.zero.letaomallspringboot.exception;

import cn.zero.letaomallspringboot.common.Result;
import cn.zero.letaomallspringboot.Constant.ResultCode;

import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import static cn.zero.letaomallspringboot.common.Result.fail;

@ControllerAdvice("cn.zero.letaomallspringboot.controller")
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 处理所有运行时异常和系统异常
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result<Object> handleException(Exception e, HttpServletRequest request) {
        String timestamp = LocalDateTime.now().format(DATE_TIME_FORMATTER);
        String requestURI = request != null ? request.getRequestURI() : "unknown";
        String method = request != null ? request.getMethod() : "unknown";
        
        // 记录详细的异常信息
        log.error("========== 系统异常 ==========");
        log.error("异常时间: {}", timestamp);
        log.error("请求路径: {} {}", method, requestURI);
        log.error("异常类型: {}", e.getClass().getName());
        log.error("异常消息: {}", e.getMessage());
        log.error("异常堆栈: ", e);
        log.error("=============================");
        
        return fail(ResultCode.SYSTEM_ERROR, e.getMessage());
    }

    /**
     * 处理自定义业务异常
     */
    @ExceptionHandler(value = CustomException.class)
    @ResponseBody
    public Result<Object> handleCustomException(CustomException e, HttpServletRequest request) {
        String timestamp = LocalDateTime.now().format(DATE_TIME_FORMATTER);
        String requestURI = request != null ? request.getRequestURI() : "unknown";
        String method = request != null ? request.getMethod() : "unknown";
        
        // 记录自定义异常的详细信息
        log.error("========== 自定义业务异常 ==========");
        log.error("异常时间: {}", timestamp);
        log.error("请求路径: {} {}", method, requestURI);
        log.error("异常代码: {}", e.getCode());
        log.error("异常消息: {}", e.getMsg());
        log.error("异常类型: {}", e.getClass().getName());
        log.error("异常堆栈: ", e);
        log.error("===================================");
        
        return fail(e.getCode(), e.getMsg());
    }

    /**
     * 处理运行时异常（RuntimeException）
     */
    @ExceptionHandler(value = RuntimeException.class)
    @ResponseBody
    public Result<Object> handleRuntimeException(RuntimeException e, HttpServletRequest request) {
        String timestamp = LocalDateTime.now().format(DATE_TIME_FORMATTER);
        String requestURI = request != null ? request.getRequestURI() : "unknown";
        String method = request != null ? request.getMethod() : "unknown";
        
        // 记录运行时异常的详细信息
        log.error("========== 运行时异常 ==========");
        log.error("异常时间: {}", timestamp);
        log.error("请求路径: {} {}", method, requestURI);
        log.error("异常类型: {}", e.getClass().getName());
        log.error("异常消息: {}", e.getMessage());
        log.error("异常堆栈: ", e);
        log.error("===============================");
        
        return fail(ResultCode.SYSTEM_ERROR, e.getMessage());
    }

}
